package mq

import (
	"context"
	"fmt"
	"github.com/nsqio/go-nsq"
	s_pb "ldaccount/api/pb/server"
	"ldaccount/internal/service"
	"ldaccount/pkg/mq"
)

const (
	OpenTicketSub = "open-ticket_subscribed"
)

// MqHandler mq handler
type mqHandler struct {
	*MqBase
	name string
}

// NewMqHandler new mq handler
func NewMqHandler() *mqHandler {
	return &mqHandler{
		MqBase: base,
		name:   "nsq_handler",
	}
}

// RegisterHandler 注册topic
func (h *mqHandler) RegisterHandler(c *mq.NsqConsumer) {
	if err := c.Register("bilinaccount-say_hello", "test", h.wrap("bilinaccount-say_hello", h.sayHello), 1); err != nil {
		h.logger.Bg().Panic(fmt.Sprintf("topic bilinaccount-say_hello start error: %s", err.Error()))
	}
	// 公众号扫描消息
	if err := c.Register(OpenTicketSub, "account", h.wrap(OpenTicketSub, h.wechatMqFollowMsg), 5); err != nil {
		h.logger.Bg().Panic(fmt.Sprintf("topic open-ticket_subscribed start error: %s", err.Error()))
	}
}

func (h *mqHandler) sayHello(ctx context.Context, msg *nsq.Message) error {
	req := &s_pb.HelloRequest{}
	if errL := h.ParseBody(msg.Body, req); errL != nil {
		return errL
	}
	h.logger.For(ctx).Info(fmt.Sprintf("hello: %s, id: %d", req.Name, req.Id))
	return nil
}

// 微信公众号关注消息
func (h *mqHandler) wechatMqFollowMsg(ctx context.Context, msg *nsq.Message) error {
	req := &s_pb.MqFollowRequest{}
	if errL := h.ParseBody(msg.Body, req); errL != nil {
		return errL
	}
	errL := service.GetAccountsSrv().SavePlatformUserInfo(ctx, req.Ticket, h.cfg.Biz.MpAppId, req.OpenId,
		req.UnionId, req.Nickname, req.Avatar, "wechat_mp")
	return errL
}
